//list 添加 list
const addAll = (itemList, addItemList) => {
    if (!itemList) {
        itemList = []
    }
    if (itemList.length === 0) {
        itemList = addItemList
    } else {
        for (let i = 0; i < addItemList.length; i++) {
            const addItem = addItemList[i]
            itemList.push(addItem)
        }
    }
    return itemList
}

const imageListHandler = (value) => {
    let imageItemList = []
    if (value) {
        try {
            if (value instanceof Array) {
                value.forEach(image => {
                    const {id, url} = image
                    let type = 'image'
                    if (url && url.indexOf('.mp4') > 0) {
                        type = 'video'
                    }
                    const imageItem = {id: id, type: type, url: url}
                    imageItemList.push(imageItem)
                })
            }
        } catch(error) {
            console.log(error)
        }
    }
    return imageItemList
}

const checkEmail = (value) => {
    return value && /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(value)
}

const checkNumber = (value) => {
    return value && /[\d]/.test(value)
}

const numberFormatter = (value) => {
    return value ? String(value.replace(/(\d{1,3})(?=(\d{3})+(?:$|\.))/g, '$1,')) : '0'
}

const getUrlType = (url) => {
    let type = 'image'
    if (url) {
        if (url.indexOf('.mp4') > 0 || url.indexOf('.mov') > 0) {
            type = 'video'
        }
    }
    return type
}

const typeIsVideo = (type) => {
    return 'video' === type
}

const setLoginUser = (data) => {
    const {access_token} = data
    if (access_token) {
        localStorage.setItem('token', access_token);
    }
    localStorage.setItem('loginUser', JSON.stringify(data));

}

const logout = () => {
    localStorage.removeItem('token')
    localStorage.removeItem('loginUser')
}
const getLoginUser = () => {
    const {id, name, email, head_image_url, password, phone_number, access_token, is_admin} = JSON.parse(localStorage.getItem("loginUser"))
    return {
        id: id,
        name: name,
        email: email,
        avatar: head_image_url,
        password: password,
        phone: phone_number,
        isAdmin: is_admin === 1,
        accessToken: access_token,
    }
}

export default function(Vue) {
    //添加全局API
    Vue.prototype.$baseJS = {
        addAll,
        imageListHandler,
        numberFormatter,
        setLoginUser,
        getLoginUser,
        checkEmail,
        checkNumber,
        logout,
        getUrlType,
        typeIsVideo,
    }
}